package duoxiancheng;

/**
 * 线程安全：在并发时保证数据的正确性，效率尽可能的高
 * synchronized
 * 1.同步方法
 * 2.同步块
 */
public class synTest01 {
    public static void main(String[] args) {
        //一份资源
        safe12306 w06= new safe12306();
        //多个代理
        new Thread(w06,"问问").start();
        new Thread(w06,"大幅度").start();
        new Thread(w06,"天天").start();
    }
}
//线程安全  同步  成员方法，锁的是this，锁的资源(对象的资源)
class safe12306 implements Runnable{
    private int ticket = 10;
    private Boolean flag =true;

    @Override
    public void run() {
        while (flag){
            test();
        }
    }

    public synchronized void test(){
        if (ticket<=0){
            flag=false;
            return;
        }
        try {//模拟网络延迟，高并发
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println( Thread.currentThread().getName()+"---->"+ticket--);
    }
}